package com.cndw.kungfu.controller;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.comm.AccessClose;
import com.cndw.kungfu.comm.AccessFlag;
import com.cndw.kungfu.comm.CommInspection;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCore;
import com.cndw.kungfu.config.ConstantsFlag;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Npc;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Script;
import com.cndw.kungfu.exception.ConstTypeException;
import com.cndw.kungfu.ext.JsonProcesser;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.MD5;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.StringProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.business.IPayManager;
import com.cndw.kungfu.model.business.domain.PayGoods;
import com.cndw.kungfu.model.goods.DiscountCenter;
import com.cndw.kungfu.model.goods.GoodsManager;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.goods.domain.Discount;
import com.cndw.kungfu.model.goods.domain.ExchangeShop;
import com.cndw.kungfu.model.goods.domain.HeroShop;
import com.cndw.kungfu.model.goods.domain.SysModeAwards;
import com.cndw.kungfu.model.goods.domain.WarShop;
import com.cndw.kungfu.model.sys.LogManager;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.model.task.PrestigeGoods;
import com.cndw.kungfu.vo.DiscountVO;
import com.cndw.kungfu.vo.PrestigeVO;
import com.cndw.kungfu.vo.goodsvo.GoodsVO;
import com.cndw.kungfu.vo.goodsvo.SubPopsVO;
import com.cndw.openqq.client.ClientRequest;
import com.cndw.openqq.client.ClientURI;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 关于道具的一些接口,和GoodsController类似
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2011-9-22 下午4:53:39
 */
@Controller
public class ShopController {
	@Autowired
	private GoodsManager goodsManager;
	@Autowired
	private LogManager logManager;
	@Autowired
	private IPayManager iPayManager;

	/**
	 * npc购买信息
	 * 
	 * @param session
	 * @param npcId
	 * @param scriptId
	 * @return
	 */
	public ResponseMessage npcShop(Session session, int npcId, int scriptId) {
		Map<String, Object> map = new HashMap<String, Object>();

		Script script = Context.getCongfigServer().getScript(scriptId);
		int[] parameters = script.getParametersLongArr();
		List<GoodsVO> saleList = new ArrayList<GoodsVO>();
		if (parameters != null) {
			for (int id : parameters) {
				GoodsMode goodsMode = Context.getGoodsServer().getModeById(id);
				if (goodsMode == null || !goodsMode.isBuyEnable()) {
					continue;
				}
				saleList.add(goodsMode.toGoodsVO());
			}
		}

		map.put("saleList", saleList);
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.shopNpc);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 出售给npc
	 * 
	 * @param session
	 * @return
	 */
	@AccessFlag(ConstantsFlag.npcSale)
	public ResponseMessage npcSale(Session session, int storagePlace) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}
		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		Goods goods = playerBoxs.get(storagePlace);
		if (goods == null) {
			return null;
		}
		if (goods.getGoodsMode().getNpcRecover() <= 0) {
			return null;
		} else if (goods.getStackNum() > goods.getGoodsMode().getMaxStack()) {
			return null;
		}
		int num = goods.getStackNum();
		playerBoxs.remove(storagePlace);

		int alter = goods.getGoodsMode().getNpcRecover() * num;
		player.alterAsset(alter);
		player.commitSync();
		LogServer.recordLog(player, ConstantsLog.goods, 70024, goods.getGoodsMode().getName(), num, alter, player.getAsset());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alter", alter);
		map.put("asset", player.getAsset());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 商城内容
	 * 
	 * @param session
	 * @param typeId
	 *            道具类别
	 * @param page
	 *            页数
	 * @param pageSize
	 *            每页条数
	 * @return
	 */
	public ResponseMessage shop(Session session, int typeId, int page, int pageSize) {
		Map<String, Object> map = new HashMap<String, Object>();

		List<GoodsVO> result = goodsManager.getAllSaLeist(typeId);
		int offset = (page - 1) * pageSize;
		if (result == null || offset > result.size()) {
			return ResponseMessage.getSuccMessage(false);
		}
		int limit = offset + pageSize;
		if (limit > result.size()) {
			limit = result.size();
		}
		List<GoodsVO> saleList = result.subList(offset, limit);
		int counts = result.size();

		map.put("saleList", saleList);
		map.put("counts", counts);
		map.put("page", page);
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.shopMain);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 商城左侧新品推荐
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage shopLeft(Session session) {

		Map<String, Object> map = new HashMap<String, Object>();
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		map.put("shopHotIds", ConstantsConfig.getShopHotIds());
		map.put("shopNewIds", ConstantsConfig.getShopNewIds());

		map.put("vipScore", player.getVipScore());
		map.put("payCash", iPayManager.selectPayGoldSum(session.getUid()));

		map.put("payCashUpgrade", 0);

		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 我的购买历史
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage showHistory(Session session) {
		List<Integer> buyIds = logManager.getBuyIds(session.getUid());
		if (buyIds == null || buyIds.isEmpty()) {
			return null;
		}
		List<GoodsVO> result = new ArrayList<GoodsVO>();
		for (Integer goodsId : buyIds) {
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
			if (goodsMode != null) {
				result.add(goodsMode.toGoodsVO());
			}
		}

		return ResponseMessage.getSuccMessage(result);
	}

	/**
	 * 购买物品
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	@AccessFlag(ConstantsFlag.buy)
	public ResponseMessage buy(Session session, int goodsId, int num, int usePaytype) {
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (goodsMode == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		if (num <= 0) {
			return null;
		}

		if (!goodsMode.isBuyEnable()) {
			return null;
		} else if (goodsMode.getPaytype() == 0) {
			return null;
		}

		if (goodsMode.getPaytype() == 0 || (usePaytype & goodsMode.getPaytype()) <= 0) {// 是否有这种支付方式
			return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.buy.payerr"));
		}

		// 需要空格数
		int size = NumberProcesser.ceil(num, goodsMode.getMaxStack());
		if (!player.getPlayerBoxs().checkBlack(size)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", size));
		}

		if (goodsMode.getBuyLimit() > 0) {
			if (num > goodsMode.getBuyLimit()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("goods.buy.limit", goodsMode.getBuyLimit()));
			}
			if (TimeProcesser.getUnixTime() >= ConstantsCore.getActivityEnd()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.timeout"));
			}
			// int lastTime =
			// Context.getSyncServer().selectLastBuyTime(player.getPlayerId(),
			// ConstantsCore.buyLimitId);
			int lastTime = Context.getSyncServer().selectLastBuyTime(player.getPlayerId(), goodsId);
			if (lastTime >= TimeProcesser.getMorningTime()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("goods.buy.limit", goodsMode.getBuyLimit()));
			}
		}

		boolean constGold = false;
		boolean constAsset = false;
		boolean constVipScore = false;
		boolean buyBing = false;
		// 支付方式包括哪些
		if ((usePaytype & Constants.PAY_GOLD) > 0) {
			constGold = true;
		} else if ((usePaytype & Constants.PAY_ASSET) > 0) {
			constAsset = true;
		} else if ((usePaytype & Constants.PAY_VipScore) > 0) {
			constVipScore = true;
		}
		int gold = 0, asset = 0, vipScore = 0;
		try {
			if (constGold) {
				gold = goodsMode.getGold() * num;
				if (gold <= 0) {
					throw new ConstTypeException();
				} else if (player.getGoldAll() < gold) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.buy.noenoughgold"));
				}
				buyBing = player.getGoldBing() > 0;
			}

			if (constAsset) {
				asset = goodsMode.getAsset() * num;
				if (asset <= 0) {
					throw new ConstTypeException();
				} else if (player.getAsset() < asset) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.buy.noenoughsliver"));
				}
			}

			if (constVipScore) {
				vipScore = goodsMode.getVipScore() * num;
				if (vipScore <= 0) {
					throw new ConstTypeException();
				} else if (player.getVipScore() < vipScore) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.buy.noenoughvipsocre"));
				}
			}

			if (constGold) {
				player.alterGoldAll(-gold);
			}
			if (constAsset) {
				player.alterAsset(-asset);
			}
			if (constVipScore) {
				player.alterVipScore(-vipScore);
			}
		} catch (ConstTypeException e) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.buy.payerr"));
		}
		if (goodsId == 103031) {
			Context.getTaskServer().notifyToSpark(player.getPlayerId(), ConstantsTask.spark25Shop, 1);
		}

		if (gold > 5) {// 增加商城积分
			//player.alterVipScore(gold / 5);
		}
		Context.getGoodsServer().giveGoodsBing(session.getUid(), goodsId, num, buyBing ? 1 : 0);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("goldTicke", player.getGoldTicke());
		map.put("asset", player.getAsset());
		map.put("vipScore", player.getVipScore());

		player.commitSync();// 提交同步
		// 添加“道具-商城购买”日志
		LogServer.recordLog(player, ConstantsLog.goods, 70001, usePaytype, goodsMode.getName(), goodsId, num, gold, vipScore, asset);
		if (constGold || constVipScore) {
			LogServer.costLog(player.getPlayerId(), usePaytype, gold, 0, vipScore, goodsId, num);
			QQDC.getInstance().cost(player, gold, goodsId, goodsMode.getGoodTypeId(), num);
		} else if (constAsset) {
			Context.getTaskServer().notifyToSpark(session.getUid(), ConstantsTask.spark37BuyHp, 1);

		}

		String title = LanguageLib.get("goods.buy.suc", num, goodsMode.getName());
		return ResponseMessage.ticpMsg(title, map);
	}

	/**
	 * 快速购买
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage fastShop(Session session, int type) {

		int[] goodsIds = null;
		switch (type) {
		case 101:// 黄金武状元令
			goodsIds = new int[] { 103997, 103998, 103999 };
			break;
		case 102:// 收徒令
			goodsIds = new int[] { GoodsEffectConfig.getDiscipleReinGoodsId() };
			break;
		case 103:// 任务品质刷新
			goodsIds = GoodsEffectConfig.taskQualityIds;
			break;
		case 104:// 徒弟经验丹
			goodsIds = GoodsEffectConfig.getExpgoodsids();
			break;
		case 105:// 传送符
			goodsIds = new int[] { GoodsEffectConfig.sceneTeleportId };
			break;
		case 106:// 聚命散
			goodsIds = new int[] { 103913, 103912 };
			break;
		case 107:// 聚香散
			goodsIds = new int[] { 103903, 103902 };
			break;

		// 201 命中 202闪避 203暴击 204 韧性 205攻击 206防御 207生命 208魔法 209速度
		case 201:
			goodsIds = GoodsEffectConfig.hitDrugGoodsId;
			break;
		case 202:
			goodsIds = GoodsEffectConfig.dodgDrugGoodsId;
			break;
		case 203:
			// goodsIds = GoodsEffectConfig.critDrugGoodsId;
			break;
		case 204:
			// goodsIds = GoodsEffectConfig.toughDrugGoodsId;
			break;
		case 205:
			goodsIds = GoodsEffectConfig.atkDrugGoodsId;
			break;
		case 206:
			goodsIds = GoodsEffectConfig.defDrugGoodsId;
			break;
		case 207:
			goodsIds = GoodsEffectConfig.hpDrugGoodsId;
			break;
		case 209:
			goodsIds = GoodsEffectConfig.spdDrugGoodsId;
			break;
		case 301:// 宠物喂养丹
			goodsIds = new int[] { 103301, 103302, 103303 };
			break;
		case 302:// 宠物培养丹
			goodsIds = new int[] { 103304, 103305, 103306 };
			break;

		case 401:// 首冲礼包显示的物品
			goodsIds = new int[] { 103996 };
			break;
		case 501:// 端午活动奖励
		case 504:
			goodsIds = new int[] { 103506, 103304, 103301, 103019, 103004, 103504, 103911, 103901 };
			break;
		case 502:// 端午活动奖励
			goodsIds = new int[] { 103506, 20300101, 20301101, 20302101, 104005, 103305, 103303, 103021, 103007, 103507 };
			break;
		case 503:// 端午活动奖励
			goodsIds = new int[] { 103506, 104006, 104007, 20302101 };
			break;
		case 505:
			goodsIds = ConstantsModel.zzLiQuanAwardIds;
			break;
		case 506:// 情人节活动送花奖励
			goodsIds = new int[] { 20304111, 20304112, 20304113, 20304114 };
			break;
		case 507:// 中秋赏月奖励
			goodsIds = new int[] { 103560, 103536, 103537, 103541 };
		case 508:// 风筝奖励物品
			goodsIds = new int[] { 103581, 103582, 103583, 103584 };
			break;
		case 509:// 秦淮诗会奖励物品
			goodsIds = ConstantsModel.poetryAwardIds;
			break;
		case 601:
			goodsIds = new int[] { 104003, 104002, 103301, 103995, 103502 };
			break;
		default:
			break;
		}
		PlayerBoxs playerBoxs = Context.getGoodsServer().getPlayerBoxs(session.getUid());
		List<GoodsVO> goodsVOs = new ArrayList<GoodsVO>();
		for (int goodsId : goodsIds) {
			GoodsVO goodsVO = new GoodsVO(goodsId, session.getUid(), 0);

			if (type != 401) {
				int stackNum = playerBoxs.getStackNum(goodsId);
				goodsVO.setStackNum(stackNum);
			}

			goodsVOs.add(goodsVO);
		}

		return ResponseMessage.getSuccMessage(goodsVOs);
	}

	public ResponseMessage fastShopGoodsMode(Session session, int goodsId) {
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		if (goodsMode == null) {
			return null;
		}
		GoodsVO goods = goodsMode.toGoodsVO();
		return ResponseMessage.getSuccMessage(goods);
	}

	public ResponseMessage fastShopIds(Session session, String idsStr) {
		int[] ids = StringProcesser.toIntArray(idsStr);
		if (ids == null || ids.length >= 15) {
			return null;
		}

		List<GoodsVO> goodsVOs = new ArrayList<GoodsVO>();
		for (int goodsId : ids) {
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
			if (goodsMode == null) {
				continue;
			}
			GoodsVO goods = goodsMode.toGoodsVO();
			goodsVOs.add(goods);
		}
		return ResponseMessage.getSuccMessage(goodsVOs);
	}

	/**
	 * 显示奖励物品
	 * 
	 * @param session
	 * @param rootId
	 * @param typeId
	 * @return
	 */
	public ResponseMessage fastSubPops(Session session, int rootId, int typeId) {
		if (rootId < 0 || typeId < 0) {
			return null;
		}
		SysModeAwards awards = SysModeAwards.get(rootId, typeId);
		if (awards == null) {
			return null;
		}
		SubPopsVO subPopsVO = Context.getGoodsServer().makeAwards(awards.getSubPopsList());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("subPops", subPopsVO);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示声望道具兑换的列表
	 * 
	 * @param npcId
	 * @param scriptId
	 * @return
	 */
	public ResponseMessage prestigeGoodsList(Session session, int npcId, int scriptId) {
		Npc npc = Context.getSceneServer().getNpcById(npcId);
		if (npc == null) {
			return null;
		}
		int sceneId = npc.getSceneId();
		Collection<PrestigeGoods> dataList = PrestigeGoods.getListBySceneId(sceneId);
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		int playerPrestige = player.getDataInfo().getPrestige(sceneId);

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("prestigeGoods", dataList);
		data.put("playerPrestige", playerPrestige);
		data.put("prestigeLevel", PrestigeVO.getVO(playerPrestige));

		QQDC.getInstance().logClick(player, LogFieldType.shopPrestige);

		return ResponseMessage.getSuccMessage(data);
	}

	/**
	 * 执行声望道具兑换
	 * 
	 * @param id
	 * @return
	 */
	@AccessFlag(ConstantsFlag.prestigeGood)
	public ResponseMessage prestigeGoodsExchange(Session session, int id) {
		PrestigeGoods prestigeGoods = PrestigeGoods.getOnePrestigeGoods(id);
		if (prestigeGoods == null) {
			return null;
		}
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		int playerPrestige = player.getDataInfo().getPrestige(prestigeGoods.getSceneId());
		int playerPrestigeLevel = NumberProcesser.nearMaxIndex(ConstantsConfig.getPrestigeValues(), playerPrestige);
		if (player.getGoldTicke() < prestigeGoods.getGoldTicke()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.goldticke"));
		}
		if (playerPrestigeLevel < prestigeGoods.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.prestige.level"));
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(prestigeGoods.getGoodsId());
		// 需要空格数
		int size = 1;
		if (!player.getPlayerBoxs().checkBlack(size)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", size));
		}
		player.alterGoldTicke(-prestigeGoods.getGoldTicke());

		Context.getGoodsServer().giveGoodsBing(playerId, prestigeGoods.getGoodsId(), 1, 1);

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("goldTicke", player.getGoldTicke());
		player.commitSync();// 提交同步

		// 添加"道具-声望兑换"日志
		LogServer.recordLog(player, ConstantsLog.goods, 70002, goodsMode.getName(), prestigeGoods.getGoldTicke());

		LogServer.costLog(player.getPlayerId(), Constants.PAY_GOLDTICKE, 0, prestigeGoods.getGoldTicke(), 0, prestigeGoods.getGoodsId(), 1);

		return ResponseMessage.getSuccMessage(data);
	}

	/**
	 * 武道令商店
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage warShop(Session session, int type) {
		Collection<WarShop> list = WarShop.getAll();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("warShopGoodsId", GoodsEffectConfig.warTokenGoodsId);
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.shopWar);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 武道令兑换
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	@AccessFlag(ConstantsFlag.warBuy)
	public ResponseMessage warShopBuy(Session session, int id, int num) {
		WarShop warShop = WarShop.getOne(id);
		if (warShop == null || num < 1) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < warShop.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.war.level"));
		}
		int keyId = GoodsEffectConfig.warTokenGoodsId;
		int haveCount = player.getPlayerBoxs().getStackNum(keyId);
		int costCount = warShop.getCost() * num;
		if (haveCount < costCount || costCount <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.war.count"));
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(warShop.getGoodsId());
		GoodsMode costMode = Context.getGoodsServer().getModeById(GoodsEffectConfig.warTokenGoodsId);
		// 需要空格数
		int size = NumberProcesser.ceil(num, goodsMode.getMaxStack());
		if (!player.getPlayerBoxs().checkBlack(size)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", size));
		}

		player.getPlayerBoxs().costGoods(keyId, costCount);
		Context.getGoodsServer().giveGoodsBing(session.getUid(), warShop.getGoodsId(), num, 1);

		LogServer.recordLog(player, ConstantsLog.goods, 70021, goodsMode.getName(), num, costCount, haveCount, costMode.getName());

		return ResponseMessage.getSuccMessage(true);
	}

	public ResponseMessage heroShop(Session session, int type, int costId) {
		Collection<HeroShop> list = HeroShop.getAll();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("costId", costId);
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.shopHero);
		return ResponseMessage.getSuccMessage(map);
	}

	@AccessFlag(ConstantsFlag.heroBuy)
	public ResponseMessage heroShopBuy(Session session, int id, int num) {
		HeroShop heroShop = HeroShop.getOne(id);
		if (heroShop == null || num <= 0) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int haveCount = player.getPlayerBoxs().getStackNum(heroShop.getCostId());
		int costCount = heroShop.getCost() * num;
		if (haveCount < costCount || costCount <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("show.hero.num"));
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(heroShop.getGoodsId());
		GoodsMode costMode = Context.getGoodsServer().getModeById(heroShop.getCostId());
		// 需要空格数
		int size = NumberProcesser.ceil(num, goodsMode.getMaxStack());
		if (!player.getPlayerBoxs().checkBlack(size)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", size));
		}

		player.getPlayerBoxs().costGoods(heroShop.getCostId(), costCount);
		Context.getGoodsServer().giveGoodsBing(session.getUid(), heroShop.getGoodsId(), num, 1);

		LogServer.recordLog(player, ConstantsLog.goods, 70025, goodsMode.getName(), num, costCount, haveCount, costMode.getName());

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 通用兑换商店
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage exchangeShop(Session session, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Collection<ExchangeShop> list = ExchangeShop.getAll(type);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		if (type == 1) {// 收徒积分兑换
			map.put("score", player.getDataInfo().intDataGet(ConstantsIntKey.trd));
		}
		QQDC.getInstance().logClick(player, LogFieldType.exchangeShop);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 通用物品兑换
	 * 
	 * @param session
	 * @param type
	 * @param id
	 * @param num
	 * @return
	 */
	public ResponseMessage exchangeShopBuy(Session session, int type, int id, int num) {
		ExchangeShop exchangeShop = ExchangeShop.getOne(type, id);
		if (exchangeShop == null || num <= 0) {
			return null;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<String, Object> map = new HashMap<String, Object>();
		switch (type) {
		case 1:// 徒弟积分兑换
			int haveCount = player.getDataInfo().intDataGet(ConstantsIntKey.trd);// 积分
			int costCount = exchangeShop.getCost() * num;
			if (haveCount < costCount) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("shop.exchange.disscore"));
			}
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(exchangeShop.getGoodsId());

			int size = NumberProcesser.ceil(num, goodsMode.getMaxStack());
			if (!player.getPlayerBoxs().checkBlack(size)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", size));
			}
			player.getDataInfo().intDataAlter(ConstantsIntKey.trd, -costCount);
			player.getDataInfo().commitSync();
			Context.getGoodsServer().giveGoodsBing(session.getUid(), exchangeShop.getGoodsId(), num, 1);

			LogServer.recordLog(player, ConstantsLog.goods, 70028, goodsMode.getName(), num, costCount, player.getDataInfo().intDataGet(ConstantsIntKey.trd));
			map.put("score", player.getDataInfo().intDataGet(ConstantsIntKey.trd));
			break;

		default:
			break;
		}

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 道具兑换中心
	 * 
	 * @param session
	 * @param goodsId
	 * @return
	 */
	public ResponseMessage exchangeCenter(Session session, int goodsId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int[] config = GoodsEffectConfig.getExchangeConfig(goodsId);
		if (config == null) {
			return null;
		}
		int haveNum = player.getPlayerBoxs().getStackNum(goodsId);
		if (haveNum < config[0]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.goods"));
		}
		if (!player.getPlayerBoxs().checkBlack(1)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		player.getPlayerBoxs().costGoods(goodsId, config[0]);
		Context.getGoodsServer().giveGoods(session.getUid(), config[1], 1);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("costNum", config[0]);
		map.put("gotNum", 1);

		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage discountList(Session session) {
		if (session.getUid() >= 0) {
			return null;
		}
		Set<Integer> ids = DiscountCenter.getIds();
		List<DiscountVO> list = new ArrayList<DiscountVO>();
		for (int id : ids) {
			Discount discount = Discount.getOne(id);
			int goodsId = discount.getGoodsId();
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
			DiscountVO discounVO = new DiscountVO();
			discounVO.setGoodsVO(goodsMode.toGoodsVO());
			discounVO.setId(discount.getId());
			discounVO.setDiscount(discount.getDiscount());
			boolean ok = DiscountCenter.canBuy(session.getUid(), id);
			int leftNum = discount.getMax() - DiscountCenter.getHaveNum(id);

			discounVO.setOk(ok);
			discounVO.setLeftNum(leftNum);
			list.add(discounVO);

		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("nextRefreshTime", DiscountCenter.getNextRefreshTime());
		return ResponseMessage.getSuccMessage(map);
	}

	@AccessFlag(ConstantsFlag.discount)
	@AccessClose
	public ResponseMessage discountBuy(Session session, int id) {
		if (session.getUid() >= 0) {
			return null;
		}
		Discount discount = Discount.getOne(id);
		if (discount == null) {
			return null;
		}
		boolean ok = DiscountCenter.canBuy(session.getUid(), id);
		if (!ok || DiscountCenter.getHaveNum(id) >= discount.getMax()) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int costGold = discount.getDiscount();
		int goodsId = discount.getGoodsId();
		int num = 1;
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(goodsId);
		if (!goodsMode.isBuyEnable() || costGold < 0) {
			return null;
		}
		if (player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		if (!player.getPlayerBoxs().checkBlack()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		player.alterGoldAll(-costGold);

		Context.getGoodsServer().giveGoodsBing(session.getUid(), goodsId, num, 1);
		DiscountCenter.buyRecord(session.getUid(), id);

		int leftNum = discount.getMax() - DiscountCenter.getHaveNum(id);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("leftNum", leftNum);

		player.commitSync();// 提交同步
		int usePaytype = Constants.PAY_Discount;
		// 添加“道具-商城购买”日志
		LogServer.recordLog(player, ConstantsLog.goods, 70001, usePaytype, goodsMode.getName(), goodsId, num, costGold, 0, 0);
		if (costGold > 0) {
			LogServer.costLog(player.getPlayerId(), usePaytype, costGold, 0, 0, goodsId, num);
			QQDC.getInstance().cost(player, costGold, goodsId, goodsMode.getGoodTypeId(), num);
		}
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage payBuyShow(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.winPay);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pay500First", false);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 购买物品
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage payBuyGoods(Session session, int id) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		PayGoods goods = PayGoods.getPayGoods(id);
		if (BlankUtils.isBlank(goods)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.pay.paysuit") + "!");
		}
		if (player.getDataInfo().isGmLogin() || player.getDataInfo().getPfKey().length() != 32) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.pay.fail") + "!");
		}

		// Data
		StringBuilder data = new StringBuilder();
		data.append(ConstantsConfig.getSysCgCrossURL());
		data.append("openapi?action=buyGoods");
		data.append("&openId=").append(player.getAccountName());
		data.append("&openKey=").append(player.getDataInfo().getOpenKey());
		data.append("&platform=").append(player.getDataInfo().getPf());
		data.append("&pfKey=").append(player.getDataInfo().getPfKey());
		data.append("&serverId=").append(ConstantsConfig.getSysCgSvrId());
		data.append("&userip=").append(player.getLastIp());

		data.append("&payitem=");
		data.append(goods.getId() + "*" + goods.getPrice() + "*1");// 物品id,价格q点,数量
		data.append("&appmode=").append(goods.getAppmode());// 购买模式
		data.append("&goodsmeta=").append(goods.getGoodsmeta());
		data.append("&goodsurl=").append(goods.getGoodsurl());
		data.append("&amt=").append(goods.getPrice());
		data.append("&zoneid=").append("0");

		data.append("&sign=");
		data.append(MD5.compile(player.getAccountName().concat(ConstantsConfig.getSysCgKeyPlatform())));
		data.append("&ts=").append(TimeProcesser.getUnixTime());
		data.append("&s=").append(Math.random());

		URI uri = ClientURI.createURI(data.toString());

		String apiMsg = null;
		boolean errLog = true;
		try {
			apiMsg = ClientRequest.sendGetRequest(uri, 3000, 5000);
			if (apiMsg == null || apiMsg.indexOf(CommInspection.ret) < 0) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.pay.fail"));
			}
			Map<String, String> resultMap = JsonProcesser.objectJsonMapDecode(apiMsg, String.class, String.class);
			int ret = resultMap.containsKey(CommInspection.ret) ? Integer.valueOf(resultMap.get(CommInspection.ret).toString()) : -4444;
			if (ret == 0 && resultMap.containsKey("url_params")) {
				errLog = false;
				return ResponseMessage.getSuccMessage(resultMap.get("url_params"));
			} else {
				if (ret == 1002 || ret == 1000) {
					errLog = false;
					return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.open.notlogin"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (errLog) {
				LogUtil.getMain().debug("pay err " + player.getAccountName() + " " + apiMsg + " ");
			}
		}

		return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.pay.fail"));
	}

	/**
	 * 获取token
	 * 
	 * @param session
	 * @param type
	 * @return
	 */
	public ResponseMessage openToken(Session session, int type) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGmLogin() || player.getDataInfo().getPfKey().length() != 32) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.open.err") + "!!!");
		}
		String discountid = "MA20120730154908750";
		discountid = "MA20120730155133984";
		// Data
		StringBuilder data = new StringBuilder();
		data.append(ConstantsConfig.getSysCgCrossURL());
		data.append("openapi?action=getToken");
		data.append("&openId=").append(player.getAccountName());
		data.append("&openKey=").append(player.getDataInfo().getOpenKey());
		data.append("&platform=").append(player.getDataInfo().getPf());
		data.append("&pfKey=").append(player.getDataInfo().getPfKey());
		data.append("&serverId=").append(ConstantsConfig.getSysCgSvrId());
		data.append("&userip=").append(player.getLastIp());

		data.append("&tokentype=").append(1);
		data.append("&discountid=").append(discountid);
		data.append("&ts=").append(TimeProcesser.getUnixTime());
		data.append("&zoneid=").append(0);

		data.append("&sign=");
		data.append(MD5.compile(player.getAccountName().concat(ConstantsConfig.getSysCgKeyPlatform())));
		data.append("&s=").append(Math.random());

		URI uri = ClientURI.createURI(data.toString());

		String apiMsg = null;
		boolean errLog = true;
		try {
			apiMsg = ClientRequest.sendGetRequest(uri, 3000, 5000);
			if (apiMsg == null || apiMsg.indexOf(CommInspection.ret) < 0) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.open.err"));
			}
			Map<String, String> resultMap = JsonProcesser.objectJsonMapDecode(apiMsg, String.class, String.class);
			int ret = resultMap.containsKey(CommInspection.ret) ? Integer.valueOf(resultMap.get(CommInspection.ret).toString()) : -4444;
			if (ret == 0) {
				errLog = false;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("token", resultMap.get("token"));
				map.put("mid", resultMap.get("mid"));
				map.put("actid", discountid);
				map.put("openid", player.getAccountName());

				return ResponseMessage.getSuccMessage(map);
			} else {
				if (ret == 1002 || ret == 1000) {
					errLog = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (errLog) {
				LogUtil.getMain().debug("token err " + player.getAccountName() + " " + apiMsg);
			}
		}

		return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.open.err"));
	}

}
